import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

public class SnakeHead extends GameObj{
    private String direction = "right";

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

    public SnakeHead(int x, int y, Image img, GameFrame frame) {
        super(x, y, img, frame);
       this.frame.addKeyListener(new KeyAdapter() {
           @Override
           public void keyPressed(KeyEvent e) {
               changeDirection(e);
           }
       });
    }

    //键盘控制蛇方向
    public void changeDirection(KeyEvent keyEvent){
        switch (keyEvent.getKeyCode()){
            case KeyEvent.VK_W:
                direction = "up";
                img = GameUtils.upImg;
                break;
            case KeyEvent.VK_S:
                direction = "down";
                img = GameUtils.downImg;
                break;
            case KeyEvent.VK_D:
                direction = "right";
                img = GameUtils.rightImg;
                break;
            case KeyEvent.VK_A:
                direction = "left";
                img = GameUtils.leftImg;
                break;
        }
    }

    public void move(){
        ArrayList<SnakeBody> snakeBodies = this.frame.snakeBodies;
        for(int i = snakeBodies.size() - 1; i >= 0; i--){
            if(i == 0){//蛇身第一节
                snakeBodies.get(i).x = this.x;
                snakeBodies.get(i).y = this.y;
            }
            else {
                if (this.x == snakeBodies.get(i).x && this.y == snakeBodies.get(i).y){
                    GameFrame.state = 3;
                }
                snakeBodies.get(i).x = snakeBodies.get(i - 1).x;
                snakeBodies.get(i).y = snakeBodies.get(i - 1).y;
            }
        }

        switch (direction){
            case "right":
                x += frame.step;
                x = x > frame.frameHeight - frame.step ? 0: x;
                break;
            case "left":
                x -= frame.step;
                x = x < 0 ? frame.frameHeight - frame.step: x;
                break;
            case "up":
                y -= frame.step;
                y = y <= 0 ? frame.frameHeight - frame.step: y;
                break;
            case "down":
                y += frame.step;
                y = y > frame.frameHeight - frame.step ? frame.step: y;
                break;
        }
    }
    @Override
    public void paintSelf(Graphics graphics) {
        super.paintSelf(graphics);
        if(this.frame.foodObj.x == this.x && this.frame.foodObj.y == this.y){
            this.frame.foodObj = this.frame.getRandomFood();
            this.frame.snakeBodies.add(new SnakeBody(0,0,GameUtils.bodyImg,this.frame));
        }
        move();
    }
}
